package com.cliff.joinus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.ArgumentList;
import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.DeviceList;
import org.cybergarage.upnp.Service;
import org.cybergarage.upnp.device.DeviceChangeListener;
import org.cybergarage.upnp.device.NotifyListener;
import org.cybergarage.upnp.device.SearchResponseListener;
import org.cybergarage.upnp.event.EventListener;
import org.cybergarage.upnp.ssdp.SSDPPacket;
import org.cybergarage.upnp.std.av.controller.MediaController;
import org.cybergarage.upnp.std.av.renderer.AVTransport;
import org.cybergarage.upnp.std.av.renderer.MediaRenderer;
import org.cybergarage.upnp.std.av.server.MediaServer;
import org.cybergarage.upnp.std.av.server.object.DIDLLite;
import org.cybergarage.upnp.std.av.server.object.item.ItemNode;
import org.cybergarage.upnp.std.av.server.object.item.ResourceNode;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.common.collect.HashBiMap;

public class JoinusControlPoint extends MediaController implements
		DeviceChangeListener, EventListener, NotifyListener,
		SearchResponseListener {
	
	public static final String ACTION_DEVICE_CHANGE = "joinus.intent.action.DEVICE_CHANGE";
	public static final String EXTRA_UDN = "udn";
	public static final String EXTRA_IS_ADD = "isAdd";
	public static final String EXTRA_IS_RENDERER = "isRenderer";
	public static final String EXTRA_IS_MEDIASERVER = "isMediaServer";
	
	public static final String OBJECT_CONTAINER = "object.container";
	public static final String OBJECT_ITEM_IMAGE = "object.item.imageItem";
	public static final String OBJECT_ITEM_AUDIO = "object.item.audioItem";
	public static final String OBJECT_ITEM_VIDEO = "object.item.videoItem";

	public static final String UPNP_CLASS_IMAGE_PHOTO = "object.item.imageItem.photo";
	public static final String UPNP_CLASS_AUDIO_MUSIC = "object.item.audioItem.musicTrack";
	public static final String UPNP_CLASS_VIDEO_MOVIE = "object.item.videoItem.movie";

	public static final String UPNP_PROTOCOLINFO_PROTOCOL_HTTPGET = "http-get";
	public static final String UPNP_PROTOCOLINFO_PROTOCOL_RTSP = "rtsp-rtp-udp";
	
	protected static final int MESSAGE_STOP = 0;
	protected static final int MESSAGE_START = 1;
	protected static final int MESSAGE_SEARCH = 2;

	protected final long DEFAULT_SUBSCRIBE_SECONDS = 300;

	public static HashMap<String, String> mmtypes = new HashMap<String, String>();

	static {
		mmtypes.put("ts", "video/transportstream");
		mmtypes.put("mkv", "video/matroska-mkv");
		mmtypes.put("3gpp", "video/3gpp");
		mmtypes.put("3gp", "video/3gpp");
		mmtypes.put("3gpp2", "video/3gpp2");
		mmtypes.put("3g2", "video/3gpp2");
		mmtypes.put("ai", "application/postscript");
		mmtypes.put("aif", "audio/x-aiff");
		mmtypes.put("aifc", "audio/x-aiff");
		mmtypes.put("aiff", "audio/x-aiff");
		mmtypes.put("asc", "text/plain");
		mmtypes.put("atom", "application/atom+xml");
		mmtypes.put("au", "audio/basic");
		mmtypes.put("avi", "video/x-msvideo");
		mmtypes.put("bcpio", "application/x-bcpio");
		mmtypes.put("bin", "application/octet-stream");
		mmtypes.put("bmp", "image/bmp");
		mmtypes.put("cdf", "application/x-netcdf");
		mmtypes.put("cgm", "image/cgm");
		mmtypes.put("class", "application/octet-stream");
		mmtypes.put("cpio", "application/x-cpio");
		mmtypes.put("cpt", "application/mac-compactpro");
		mmtypes.put("csh", "application/x-csh");
		mmtypes.put("css", "text/css");
		mmtypes.put("dcr", "application/x-director");
		mmtypes.put("dif", "video/x-dv");
		mmtypes.put("dir", "application/x-director");
		mmtypes.put("djv", "image/vnd.djvu");
		mmtypes.put("djvu", "image/vnd.djvu");
		mmtypes.put("dll", "application/octet-stream");
		mmtypes.put("dmg", "application/octet-stream");
		mmtypes.put("dms", "application/octet-stream");
		mmtypes.put("doc", "application/msword");
		mmtypes.put("dtd", "application/xml-dtd");
		mmtypes.put("dv", "video/x-dv");
		mmtypes.put("dvi", "application/x-dvi");
		mmtypes.put("dxr", "application/x-director");
		mmtypes.put("eps", "application/postscript");
		mmtypes.put("etx", "text/x-setext");
		mmtypes.put("exe", "application/octet-stream");
		mmtypes.put("ez", "application/andrew-inset");
		mmtypes.put("gif", "image/gif");
		mmtypes.put("gram", "application/srgs");
		mmtypes.put("grxml", "application/srgs+xml");
		mmtypes.put("gtar", "application/x-gtar");
		mmtypes.put("hdf", "application/x-hdf");
		mmtypes.put("hqx", "application/mac-binhex40");
		mmtypes.put("htm", "text/html");
		mmtypes.put("html", "text/html");
		mmtypes.put("ice", "x-conference/x-cooltalk");
		mmtypes.put("ico", "image/x-icon");
		mmtypes.put("ics", "text/calendar");
		mmtypes.put("ief", "image/ief");
		mmtypes.put("ifb", "text/calendar");
		mmtypes.put("iges", "model/iges");
		mmtypes.put("igs", "model/iges");
		mmtypes.put("jnlp", "application/x-java-jnlp-file");
		mmtypes.put("jp2", "image/jp2");
		mmtypes.put("jpe", "image/jpeg");
		mmtypes.put("jpeg", "image/jpeg");
		mmtypes.put("jpg", "image/jpeg");
		mmtypes.put("js", "application/x-javascript");
		mmtypes.put("kar", "audio/midi");
		mmtypes.put("latex", "application/x-latex");
		mmtypes.put("lha", "application/octet-stream");
		mmtypes.put("lzh", "application/octet-stream");
		mmtypes.put("m3u", "audio/x-mpegurl");
		mmtypes.put("m4a", "audio/mp4a-latm");
		mmtypes.put("m4b", "audio/mp4a-latm");
		mmtypes.put("m4p", "audio/mp4a-latm");
		mmtypes.put("m4u", "video/vnd.mpegurl");
		mmtypes.put("m4v", "video/x-m4v");
		mmtypes.put("mac", "image/x-macpaint");
		mmtypes.put("man", "application/x-troff-man");
		mmtypes.put("mathml", "application/mathml+xml");
		mmtypes.put("me", "application/x-troff-me");
		mmtypes.put("mesh", "model/mesh");
		mmtypes.put("mid", "audio/midi");
		mmtypes.put("wma", "audio/wma");
		mmtypes.put("midi", "audio/midi");
		mmtypes.put("mif", "application/vnd.mif");
		mmtypes.put("mov", "video/quicktime");
		mmtypes.put("movie", "video/x-sgi-movie");
		mmtypes.put("mp2", "audio/mpeg");
		mmtypes.put("mp3", "audio/mpeg");
		mmtypes.put("mp4", "video/mp4");
		mmtypes.put("mpe", "video/mpeg");
		mmtypes.put("mpeg", "video/mpeg");
		mmtypes.put("mpg", "video/mpeg");
		mmtypes.put("mpga", "audio/mpeg");
		mmtypes.put("ms", "application/x-troff-ms");
		mmtypes.put("msh", "model/mesh");
		mmtypes.put("mxu", "video/vnd.mpegurl");
		mmtypes.put("nc", "application/x-netcdf");
		mmtypes.put("oda", "application/oda");
		mmtypes.put("ogg", "application/ogg");
		mmtypes.put("pbm", "image/x-portable-bitmap");
		mmtypes.put("pct", "image/pict");
		mmtypes.put("pdb", "chemical/x-pdb");
		mmtypes.put("pdf", "application/pdf");
		mmtypes.put("pgm", "image/x-portable-graymap");
		mmtypes.put("pgn", "application/x-chess-pgn");
		mmtypes.put("pic", "image/pict");
		mmtypes.put("pict", "image/pict");
		mmtypes.put("png", "image/png");
		mmtypes.put("pnm", "image/x-portable-anymap");
		mmtypes.put("pnt", "image/x-macpaint");
		mmtypes.put("pntg", "image/x-macpaint");
		mmtypes.put("ppm", "image/x-portable-pixmap");
		mmtypes.put("ppt", "application/vnd.ms-powerpoint");
		mmtypes.put("ps", "application/postscript");
		mmtypes.put("qt", "video/quicktime");
		mmtypes.put("qti", "image/x-quicktime");
		mmtypes.put("qtif", "image/x-quicktime");
		mmtypes.put("ra", "audio/x-pn-realaudio");
		mmtypes.put("ram", "audio/x-pn-realaudio");
		mmtypes.put("ras", "image/x-cmu-raster");
		mmtypes.put("rdf", "application/rdf+xml");
		mmtypes.put("rgb", "image/x-rgb");
		mmtypes.put("rm", "application/vnd.rn-realmedia");
		mmtypes.put("roff", "application/x-troff");
		mmtypes.put("rtf", "text/rtf");
		mmtypes.put("rtx", "text/richtext");
		mmtypes.put("sgm", "text/sgml");
		mmtypes.put("sgml", "text/sgml");
		mmtypes.put("sh", "application/x-sh");
		mmtypes.put("shar", "application/x-shar");
		mmtypes.put("silo", "model/mesh");
		mmtypes.put("sit", "application/x-stuffit");
		mmtypes.put("skd", "application/x-koan");
		mmtypes.put("skm", "application/x-koan");
		mmtypes.put("skp", "application/x-koan");
		mmtypes.put("skt", "application/x-koan");
		mmtypes.put("smi", "application/smil");
		mmtypes.put("smil", "application/smil");
		mmtypes.put("snd", "audio/basic");
		mmtypes.put("so", "application/octet-stream");
		mmtypes.put("spl", "application/x-futuresplash");
		mmtypes.put("src", "application/x-wais-source");
		mmtypes.put("sv4cpio", "application/x-sv4cpio");
		mmtypes.put("sv4crc", "application/x-sv4crc");
		mmtypes.put("svg", "image/svg+xml");
		mmtypes.put("swf", "application/x-shockwave-flash");
		mmtypes.put("t", "application/x-troff");
		mmtypes.put("tar", "application/x-tar");
		mmtypes.put("tcl", "application/x-tcl");
		mmtypes.put("tex", "application/x-tex");
		mmtypes.put("texi", "application/x-texinfo");
		mmtypes.put("texinfo", "application/x-texinfo");
		mmtypes.put("tif", "image/tiff");
		mmtypes.put("tiff", "image/tiff");
		mmtypes.put("tr", "application/x-troff");
		mmtypes.put("tsv", "text/tab-separated-values");
		mmtypes.put("txt", "text/plain");
		mmtypes.put("ustar", "application/x-ustar");
		mmtypes.put("vcd", "application/x-cdlink");
		mmtypes.put("vrml", "model/vrml");
		mmtypes.put("vxml", "application/voicexml+xml");
		mmtypes.put("wav", "audio/x-wav");
		mmtypes.put("wbmp", "image/vnd.wap.wbmp");
		mmtypes.put("wbmxl", "application/vnd.wap.wbxml");
		mmtypes.put("wml", "text/vnd.wap.wml");
		mmtypes.put("wmlc", "application/vnd.wap.wmlc");
		mmtypes.put("wmls", "text/vnd.wap.wmlscript");
		mmtypes.put("wmlsc", "application/vnd.wap.wmlscriptc");
		mmtypes.put("wrl", "model/vrml");
		mmtypes.put("xbm", "image/x-xbitmap");
		mmtypes.put("xht", "application/xhtml+xml");
		mmtypes.put("xhtml", "application/xhtml+xml");
		mmtypes.put("xls", "application/vnd.ms-excel");
		mmtypes.put("xml", "application/xml");
		mmtypes.put("xpm", "image/x-xpixmap");
		mmtypes.put("xsl", "application/xml");
		mmtypes.put("xslt", "application/xslt+xml");
		mmtypes.put("xul", "application/vnd.mozilla.xul+xml");
		mmtypes.put("xwd", "image/x-xwindowdump");
		mmtypes.put("xyz", "chemical/x-xyz");
		mmtypes.put("zip", "application/zip");

		mmtypes.put("aab", "application/x-authoware-bin");
		mmtypes.put("aam", "application/x-authoware-map");
		mmtypes.put("aas", "application/x-authoware-seg");
		mmtypes.put("als", "audio/X-Alpha5");
		mmtypes.put("amc", "application/x-mpeg");
		mmtypes.put("ani", "application/octet-stream");
		mmtypes.put("asd", "application/astound");
		mmtypes.put("asf", "video/x-ms-asf");
		mmtypes.put("asn", "application/astound");
		mmtypes.put("asp", "application/x-asap");
		mmtypes.put("asx", "video/x-ms-asf");
		mmtypes.put("avb", "application/octet-stream");
		mmtypes.put("awb", "audio/amr-wb");
		mmtypes.put("bld", "application/bld");
		mmtypes.put("bld2", "application/bld2");
		mmtypes.put("bpk", "application/octet-stream");
		mmtypes.put("bz2", "application/x-bzip2");
		mmtypes.put("cal", "image/x-cals");
		mmtypes.put("ccn", "application/x-cnc");
		mmtypes.put("cco", "application/x-cocoa");
		mmtypes.put("cdf", "application/x-netcdf");
		mmtypes.put("cgi", "magnus-internal/cgi");
		mmtypes.put("chat", "application/x-chat");
		mmtypes.put("clp", "application/x-msclip");
		mmtypes.put("cmx", "application/x-cmx");
		mmtypes.put("co", "application/x-cult3d-object");
		mmtypes.put("cod", "image/cis-cod");
		mmtypes.put("crd", "application/x-mscardfile");
		mmtypes.put("csm", "chemical/x-csml");
		mmtypes.put("csml", "chemical/x-csml");
		mmtypes.put("cur", "application/octet-stream");
		mmtypes.put("dcm", "x-lml/x-evm");
		mmtypes.put("dcx", "image/x-dcx");
		mmtypes.put("dhtml", "text/html");
		mmtypes.put("dot", "application/x-dot");
		mmtypes.put("dwf", "drawing/x-dwf");
		mmtypes.put("dwg", "application/x-autocad");
		mmtypes.put("dxf", "application/x-autocad");
		mmtypes.put("ebk", "application/x-expandedbook");
		mmtypes.put("emb", "chemical/x-embl-dl-nucleotide");
		mmtypes.put("embl", "chemical/x-embl-dl-nucleotide");
		mmtypes.put("eri", "image/x-eri");
		mmtypes.put("es", "audio/echospeech");
		mmtypes.put("esl", "audio/echospeech");
		mmtypes.put("etc", "application/x-earthtime");
		mmtypes.put("evm", "x-lml/x-evm");
		mmtypes.put("evy", "application/x-envoy");
		mmtypes.put("fh4", "image/x-freehand");
		mmtypes.put("fh5", "image/x-freehand");
		mmtypes.put("fhc", "image/x-freehand");
		mmtypes.put("fif", "image/fif");
		mmtypes.put("fm", "application/x-maker");
		mmtypes.put("fpx", "image/x-fpx");
		mmtypes.put("fvi", "video/isivideo");
		mmtypes.put("gau", "chemical/x-gaussian-input");
		mmtypes.put("gca", "application/x-gca-compressed");
		mmtypes.put("gdb", "x-lml/x-gdb");
		mmtypes.put("gps", "application/x-gps");
		mmtypes.put("gz", "application/x-gzip");
		mmtypes.put("hdm", "text/x-hdml");
		mmtypes.put("hdml", "text/x-hdml");
		mmtypes.put("hlp", "application/winhlp");
		mmtypes.put("hts", "text/html");
		mmtypes.put("ifm", "image/gif");
		mmtypes.put("ifs", "image/ifs");
		mmtypes.put("imy", "audio/melody");
		mmtypes.put("ins", "application/x-NET-Install");
//		mmtypes.put("ips", "application/x-ip******");
		mmtypes.put("ipx", "application/x-ipix");
		mmtypes.put("it", "audio/x-mod");
		mmtypes.put("itz", "audio/x-mod");
		mmtypes.put("ivr", "i-world/i-vrml");
		mmtypes.put("j2k", "image/j2k");
//		mmtypes.put("jad", "text/vnd.sun.j2me.app-de******or");
		mmtypes.put("jam", "application/x-jam");
		mmtypes.put("jar", "application/java-archive");
		mmtypes.put("jpz", "image/jpeg");
		mmtypes.put("jwc", "application/jwc");
		mmtypes.put("kjx", "application/x-kjx");
		mmtypes.put("lak", "x-lml/x-lak");
		mmtypes.put("lcc", "application/fastman");
		mmtypes.put("lcl", "application/x-digitalloca");
		mmtypes.put("lcr", "application/x-digitalloca");
		mmtypes.put("lgh", "application/lgh");
		mmtypes.put("lml", "x-lml/x-lml");
		mmtypes.put("lmlpack", "x-lml/x-lmlpack");
		mmtypes.put("lsf", "video/x-ms-asf");
		mmtypes.put("lsx", "video/x-ms-asf");
		mmtypes.put("m13", "application/x-msmediaview");
		mmtypes.put("m14", "application/x-msmediaview");
		mmtypes.put("m15", "audio/x-mod");
		mmtypes.put("m3url", "audio/x-mpegurl");
		mmtypes.put("ma1", "audio/ma1");
		mmtypes.put("ma2", "audio/ma2");
		mmtypes.put("ma3", "audio/ma3");
		mmtypes.put("ma5", "audio/ma5");
		mmtypes.put("map", "magnus-internal/imagemap");
		mmtypes.put("mbd", "application/mbedlet");
		mmtypes.put("mct", "application/x-mascot");
		mmtypes.put("mdb", "application/x-msaccess");
		mmtypes.put("mdz", "audio/x-mod");
		mmtypes.put("mel", "text/x-vmel");
		mmtypes.put("mi", "application/x-mif");
		mmtypes.put("mil", "image/x-cals");
		mmtypes.put("mio", "audio/x-mio");
		mmtypes.put("mmf", "application/x-skt-lbs");
		mmtypes.put("mng", "video/x-mng");
		mmtypes.put("mny", "application/x-msmoney");
		mmtypes.put("moc", "application/x-mocha");
		mmtypes.put("mocha", "application/x-mocha");
		mmtypes.put("mod", "audio/x-mod");
		mmtypes.put("mof", "application/x-yumekara");
		mmtypes.put("mol", "chemical/x-mdl-molfile");
		mmtypes.put("mop", "chemical/x-mopac-input");
		mmtypes.put("mpc", "application/vnd.mpohun.certificate");
		mmtypes.put("mpg4", "video/mp4");
		mmtypes.put("mpga", "audio/mpeg");
		mmtypes.put("mpn", "application/vnd.mophun.application");
		mmtypes.put("mpp", "application/vnd.ms-project");
		mmtypes.put("mps", "application/x-mapserver");
		mmtypes.put("mrl", "text/x-mrml");
		mmtypes.put("mrm", "application/x-mrm");
		mmtypes.put("mts", "application/metastream");
		mmtypes.put("mtx", "application/metastream");
		mmtypes.put("mtz", "application/metastream");
		mmtypes.put("mzv", "application/metastream");
		mmtypes.put("nar", "application/zip");
		mmtypes.put("nbmp", "image/nbmp");
		mmtypes.put("ndb", "x-lml/x-ndb");
		mmtypes.put("ndwn", "application/ndwn");
		mmtypes.put("nif", "application/x-nif");
		mmtypes.put("nmz", "application/x-scream");
		mmtypes.put("nokia-op-logo", "image/vnd.nok-oplogo-color");
		mmtypes.put("npx", "application/x-netfpx");
		mmtypes.put("nsnd", "audio/nsnd");
		mmtypes.put("nva", "application/x-neva1");
		mmtypes.put("oom", "application/x-AtlasMate-Plugin");
		mmtypes.put("pac", "audio/x-pac");
		mmtypes.put("pae", "audio/x-epac");
		mmtypes.put("pan", "application/x-pan");
		mmtypes.put("pcx", "image/x-pcx");
		mmtypes.put("pda", "image/x-pda");
		mmtypes.put("pfr", "application/font-tdpfr");
		mmtypes.put("pm", "application/x-perl");
		mmtypes.put("pmd", "application/x-pmd");
		mmtypes.put("pnz", "image/png");
		mmtypes.put("pot", "application/vnd.ms-powerpoint");
		mmtypes.put("pps", "application/vnd.ms-powerpoint");
		mmtypes.put("pqf", "application/x-cprplayer");
		mmtypes.put("pqi", "application/cprplayer");
		mmtypes.put("prc", "application/x-prc");
		mmtypes.put("proxy", "application/x-ns-proxy-autoconfig");
		mmtypes.put("ptlk", "application/listenup");
		mmtypes.put("pub", "application/x-mspublisher");
		mmtypes.put("pvx", "video/x-pv-pvx");
		mmtypes.put("qcp", "audio/vnd.qcelp");
		mmtypes.put("r3t", "text/vnd.rn-realtext3d");
		mmtypes.put("rar", "application/x-rar-compressed");
		mmtypes.put("rf", "image/vnd.rn-realflash");
		mmtypes.put("rlf", "application/x-richlink");
		mmtypes.put("rmf", "audio/x-rmf");
		mmtypes.put("rmm", "video/vnd.rn-realvideo");
		mmtypes.put("rmvb", "video/vnd.rn-realvideo");
		mmtypes.put("rnx", "application/vnd.rn-realplayer");
		mmtypes.put("rp", "image/vnd.rn-realpix");
		mmtypes.put("rpm", "audio/x-pn-realaudio-plugin");
		mmtypes.put("rt", "text/vnd.rn-realtext");
		mmtypes.put("rte", "x-lml/x-gps");
		mmtypes.put("rtg", "application/metastream");
		mmtypes.put("rv", "video/vnd.rn-realvideo");
		mmtypes.put("rwc", "application/x-rogerwilco");
		mmtypes.put("s3m", "audio/x-mod");
		mmtypes.put("s3z", "audio/x-mod");
		mmtypes.put("sca", "application/x-supercard");
		mmtypes.put("scd", "application/x-msschedule");
		mmtypes.put("sdf", "application/e-score");
		mmtypes.put("sea", "application/x-stuffit");
		mmtypes.put("shtml", "magnus-internal/parsed-html");
		mmtypes.put("shw", "application/presentations");
		mmtypes.put("si6", "image/si6");
		mmtypes.put("si7", "image/vnd.stiwap.sis");
		mmtypes.put("si9", "image/vnd.lgtwap.sis");
		mmtypes.put("sis", "application/vnd.symbian.install");
		mmtypes.put("slc", "application/x-salsa");
		mmtypes.put("smd", "audio/x-smd");
		mmtypes.put("smp", "application/studiom");
		mmtypes.put("smz", "audio/x-smd");
		mmtypes.put("spc", "text/x-speech");
		mmtypes.put("spr", "application/x-sprite");
		mmtypes.put("sprite", "application/x-sprite");
		mmtypes.put("spt", "application/x-spt");
		mmtypes.put("stk", "application/hyperstudio");
		mmtypes.put("stm", "audio/x-mod");
		mmtypes.put("svf", "image/vnd");
		mmtypes.put("svh", "image/svh");
		mmtypes.put("svr", "x-world/x-svr");
		mmtypes.put("swfl", "application/x-shockwave-flash");
		mmtypes.put("tad", "application/octet-stream");
		mmtypes.put("talk", "text/x-speech");
		mmtypes.put("taz", "application/x-tar");
		mmtypes.put("tbp", "application/x-timbuktu");
		mmtypes.put("tbt", "application/x-timbuktu");
		mmtypes.put("tgz", "application/x-tar");
		mmtypes.put("thm", "application/vnd.eri.thm");
		mmtypes.put("tki", "application/x-tkined");
		mmtypes.put("tkined", "application/x-tkined");
		mmtypes.put("toc", "application/toc");
		mmtypes.put("toy", "image/toy");
		mmtypes.put("trk", "x-lml/x-gps");
		mmtypes.put("trm", "application/x-msterminal");
		mmtypes.put("tsi", "audio/tsplayer");
		mmtypes.put("tsp", "application/dsptype");
		mmtypes.put("ttf", "application/octet-stream");
		mmtypes.put("ttz", "application/t-time");
		mmtypes.put("ult", "audio/x-mod");
		mmtypes.put("uu", "application/x-uuencode");
		mmtypes.put("uue", "application/x-uuencode");
		mmtypes.put("vcf", "text/x-vcard");
		mmtypes.put("vdo", "video/vdo");
		mmtypes.put("vib", "audio/vib");
		mmtypes.put("viv", "video/vivo");
		mmtypes.put("vivo", "video/vivo");
		mmtypes.put("vmd", "application/vocaltec-media-desc");
		mmtypes.put("vmf", "application/vocaltec-media-file");
		mmtypes.put("vmi", "application/x-dreamcast-vms-info");
		mmtypes.put("vms", "application/x-dreamcast-vms");
		mmtypes.put("vox", "audio/voxware");
		mmtypes.put("vqe", "audio/x-twinvq-plugin");
		mmtypes.put("vqf", "audio/x-twinvq");
		mmtypes.put("vql", "audio/x-twinvq");
		mmtypes.put("vre", "x-world/x-vream");
		mmtypes.put("vrt", "x-world/x-vrt");
		mmtypes.put("vrw", "x-world/x-vream");
		mmtypes.put("vts", "workbook/formulaone");
		mmtypes.put("wax", "audio/x-ms-wax");
		mmtypes.put("web", "application/vnd.xara");
		mmtypes.put("wi", "image/wavelet");
		mmtypes.put("wis", "application/x-InstallShield");
		mmtypes.put("wm", "video/x-ms-wm");
		mmtypes.put("wma", "audio/x-ms-wma");
		mmtypes.put("wmd", "application/x-ms-wmd");
		mmtypes.put("wmf", "application/x-msmetafile");
		mmtypes.put("wmv", "video/x-ms-wmv");
		mmtypes.put("wmx", "video/x-ms-wmx");
		mmtypes.put("wmz", "application/x-ms-wmz");
		mmtypes.put("wpng", "image/x-up-wpng");
		mmtypes.put("wpt", "x-lml/x-gps");
		mmtypes.put("wri", "application/x-mswrite");
		mmtypes.put("wrz", "x-world/x-vrml");
//		mmtypes.put("ws", "text/vnd.wap.wml******");
//		mmtypes.put("wsc", "application/vnd.wap.wml******c");
		mmtypes.put("wv", "video/wavelet");
		mmtypes.put("wvx", "video/x-ms-wvx");
		mmtypes.put("wxl", "application/x-wxl");
		mmtypes.put("x-gzip", "application/x-gzip");
		mmtypes.put("xar", "application/vnd.xara");
		mmtypes.put("xdm", "application/x-xdma");
		mmtypes.put("xdma", " application/x-xdma");
		mmtypes.put("xdw", "application/vnd.fujixerox.docuworks");
		mmtypes.put("xhtm", " application/xhtml+xml");
		mmtypes.put("xla", "application/vnd.ms-excel");
		mmtypes.put("xlc", "application/vnd.ms-excel");
		mmtypes.put("xll", "application/x-excel");
		mmtypes.put("xlm", "application/vnd.ms-excel");
		mmtypes.put("xlt", "application/vnd.ms-excel");
		mmtypes.put("xlw", "application/vnd.ms-excel");
		mmtypes.put("xm", "audio/x-mod");
		mmtypes.put("xmz", "audio/x-mod");
		mmtypes.put("xpi", "application/x-xpinstall");
		mmtypes.put("xsit", "text/xml");
		mmtypes.put("yz1", "application/x-yz1");
		mmtypes.put("z", "application/x-compress");
		mmtypes.put("zac", "application/x-zaurus-zac");		
	}

	protected static JoinusControlPoint instance = null;
	protected HandlerThread threadBackground = null;
	protected Handler handlerBackground = null;

//	protected HashBiMap<String, String> rendererSidMap = HashBiMap.create();
//	protected HashMap<String, RendererMediator> rendererMediatorMap = new HashMap<String, RendererMediator>();

	protected static final String TAG = "JoinusControlPoint";
	
	protected RendererMediator mediator = null;

	protected Context context = null;
	protected String selectedRendererUdn = null;

	public String getSelectedRendererUdn() {
		return selectedRendererUdn;
	}

	public void setSelectedRendererUdn(String selectedRendererUdn) {
		if (selectedRendererUdn == this.selectedRendererUdn)
			return;
		
		disposeRendererMediator();
		
		this.selectedRendererUdn = selectedRendererUdn;
		if (null != selectedRendererUdn) {
			mediator = new RendererMediator(this.getDevice(selectedRendererUdn));
		}
	}

	public RendererMediator getSelectedRendererMediator() {
		return mediator;
	}

	protected JoinusControlPoint() {
	}

	public synchronized static JoinusControlPoint getInstance() {
		if (null == instance) {
			instance = new JoinusControlPoint();
		}
		return instance;
	}

//	public static void clearInstance() {
//		instance = null;
//	}

	protected static class BackgroundHandler extends Handler {

		public BackgroundHandler(Looper looper) {
			super(looper);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			JoinusControlPoint cp = JoinusControlPoint.getInstance();
			switch (msg.what) {
			case MESSAGE_STOP:
				Log.d(TAG, "background HandlerThread stop");
				cp.stopWithListener();
				this.getLooper().quit();
				break;
			case MESSAGE_START:
				Log.d(TAG, "background HandlerThread start");
				cp.startWithListener();
				break;
			case MESSAGE_SEARCH:
				Log.d(TAG, "background HandlerThread search");
				cp.search();
				break;
			}
		}
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public boolean startAtBackground() {
		synchronized (this) {
			// TODO Auto-generated method stub
			if (null != handlerBackground)
				return false;

			threadBackground = new HandlerThread("ControlPoint-Background");
			// threadBackground.setDaemon(true);
			threadBackground.start();
			handlerBackground = new BackgroundHandler(
					threadBackground.getLooper());
			handlerBackground.sendEmptyMessage(MESSAGE_START);
			return true;
		}
	}

	public boolean stopAtBackground() {
		// TODO Auto-generated method stub
		synchronized (this) {
			if (null == handlerBackground)
				return false;

			handlerBackground.sendEmptyMessage(MESSAGE_STOP);
			handlerBackground = null;
			threadBackground = null;
			return true;
		}
	}

	synchronized public boolean searchAtBackground() {
		// TODO Auto-generated method stub
		if (null == handlerBackground)
			return false;

		handlerBackground.sendEmptyMessage(MESSAGE_SEARCH);
		return true;
	}

	protected void clear() {
		removeDeviceChangeListener(this);
		removeEventListener(this);
		removeNotifyListener(this);
		removeSearchResponseListener(this);

		disposeRendererMediator();
	}
	
	protected boolean startWithListener() {
		// TODO Auto-generated method stub
		clear();
		addDeviceChangeListener(this);
		addEventListener(this);
		addNotifyListener(this);
		addSearchResponseListener(this);

		return start();
	}

	protected boolean stopWithListener() {
		// TODO Auto-generated method stub
		boolean ret = stop();
		clear();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		devNodeList.clear();
		return ret;
	}

	@Override
	public void renewSubscriberService() {
		// TODO Auto-generated method stub
		Log.d(TAG, "renewSubscriberService()");
		renewSubscriberService(DEFAULT_SUBSCRIBE_SECONDS);
	}

	@Override
	protected void onRenewSubscriberServiceFailed(Device dev, Service service,
			String sid, long timeout) {
		// TODO Auto-generated method stub
		disposeRendererMediator();
		super.onRenewSubscriberServiceFailed(dev, service, sid, timeout);
	}

	@Override
	public void deviceSearchResponseReceived(SSDPPacket ssdpPacket) {
		// TODO Auto-generated method stub
		Log.d(TAG, "deviceSearchResponseReceived():" + ssdpPacket.toString());
	}

	@Override
	public void deviceNotifyReceived(SSDPPacket ssdpPacket) {
		// TODO Auto-generated method stub
		// Log.d(TAG, "deviceNotifyReceived():"+ssdpPacket.toString());
	}

	@Override
	public void eventNotifyReceived(String uuid, long seq, String varName,
			String value) {
		// TODO Auto-generated method stub
		Log.d(TAG, "eventNotifyReceived():uuid=" + uuid + ";seq=" + seq
				+ ";varName=" + varName);
		// Log.d(TAG, "eventNotifyReceived():value="+value);

		if (null != mediator)
			mediator.updateStatus(uuid, seq, varName, value);
	}

	protected void disposeRendererMediator() {
		if (null != mediator) {
			mediator.dispose();
			mediator = null;
		}
	}

	@Override
	public void deviceAdded(Device dev) {
		// TODO Auto-generated method stub

		Log.d(TAG,
				"deviceAdded():" + dev + ":" + dev.getFriendlyName() + ":"
						+ dev.getSSDPPacket().getRemoteAddress() + ":"
						+ dev.getLeaseTime() + ":" + dev.getElapsedTime());
		
		boolean isRenderer = false;
		boolean isMediaServer = false;
		if (dev.isDeviceType(MediaRenderer.DEVICE_TYPE)) {
			isRenderer = true;
		} else if (dev.isDeviceType(MediaServer.DEVICE_TYPE)) {
			isMediaServer = true;
		}

		sendDeviceChangeBroadcast(true, isRenderer, isMediaServer, dev.getUDN());
	}

	@Override
	public void deviceRemoved(Device dev) {
		// TODO Auto-generated method stub
		Log.d(TAG, "deviceRemoved():" + dev.getUDN());

		boolean isRenderer = false;
		boolean isMediaServer = false;
		if (dev.isDeviceType(MediaRenderer.DEVICE_TYPE)) {
			isRenderer = true;
			if (null != selectedRendererUdn) {
				if (selectedRendererUdn.equals(dev.getUDN())) {
					selectedRendererUdn = null;
					disposeRendererMediator();
				}
			}

		} else if (dev.isDeviceType(MediaServer.DEVICE_TYPE)) {
			isMediaServer = true;
		}
		

		sendDeviceChangeBroadcast(false, isRenderer, isMediaServer, dev.getUDN());
	}

	public boolean isRunning() {
		return (null != handlerBackground);
	}
	
	public ArrayList<String> getRendererUdnList() {
		ArrayList<String> ret = new ArrayList<String>();
		DeviceList dl = getRendererDeviceList();
		for (int i = 0; i < dl.size(); i++)
			ret.add(dl.getDevice(i).getUDN());
		return ret;
	}
	
	public ArrayList<String> getMediaServerUdnList() {
		ArrayList<String> ret = new ArrayList<String>();
		DeviceList dl = getServerDeviceList();
		for (int i = 0; i < dl.size(); i++)
			ret.add(dl.getDevice(i).getUDN());
		return ret;
	}

	protected void sendDeviceChangeBroadcast(boolean isAdd, boolean isRenderer, boolean isMediaServer, String udn) {
		if (null != context) {
			Intent intent = new Intent(ACTION_DEVICE_CHANGE);
			intent.putExtra(EXTRA_IS_ADD, isAdd);
			intent.putExtra(EXTRA_IS_RENDERER, isRenderer);
			intent.putExtra(EXTRA_IS_MEDIASERVER, isMediaServer);
			intent.putExtra(EXTRA_UDN, udn);
//			intent.setPackage(this.getClass().getPackage().getName());
			context.sendBroadcast(intent);
		}		
	}
	
	public ItemNode getItemNode(String title, String url, String protocolInfo, String upnpClass) {
		ItemNode itemNode = new ItemNode();

		itemNode.setTitle(title);
		itemNode.setResource(url, protocolInfo);
		itemNode.setUPnPClass(upnpClass);
		ResourceNode resNode = new ResourceNode();
		resNode.setValue(url);
		itemNode.addResourceNode(resNode);
		return itemNode;
	}
	
	public boolean playRenderer(ItemNode itemNode) {
		// TODO Auto-generated method stub
		if (null == itemNode) {
			Device dev = getDevice(selectedRendererUdn);		
			return play(dev);			
		}
		
		if (null == selectedRendererUdn)
			return false;
		
		Device dev = getDevice(selectedRendererUdn);		
		if (dev == null)
			return false;

		Service avTransService = dev.getService(AVTransport.SERVICE_TYPE);
		if (avTransService == null)
			return false;
		
		Action action = avTransService.getAction(AVTransport.SETAVTRANSPORTURI);
		if (action == null)
			return false;
		
		DIDLLite didl = new DIDLLite();
		didl.setContentNode(itemNode);
					
		action.setArgumentValue(AVTransport.INSTANCEID, "0");
		action.setArgumentValue(AVTransport.CURRENTURI, itemNode.getResource());
		action.setArgumentValue(AVTransport.CURRENTURIMETADATA, didl.toString());
		
		if(!action.postControlAction())
			return false;
		
		return play(dev);
	}

	public Device getSelectedRenderer() {
		return getDevice(selectedRendererUdn);		
	}	

	public boolean stopRenderer() {
		if (null == selectedRendererUdn)
			return false;
		
		Device dev = getDevice(selectedRendererUdn);		
		if (dev == null)
			return false;
		
		return stop(dev);		
	}
	
	public boolean seekRenderer(int second) {

		if (null == selectedRendererUdn)
			return false;
		
		Device dev = getDevice(selectedRendererUdn);		
		if (dev == null)
			return false;
		
		Service avTransService = dev.getService(AVTransport.SERVICE_TYPE);
		if (avTransService == null)
			return false;
		
		Action action = avTransService.getAction(AVTransport.SEEK);
		if (action == null)
			return false;
		
		int h = second / 3600;
		int m = (second % 3600) / 60;
		int s = second % 60;
		
		action.setArgumentValue(AVTransport.INSTANCEID, "0");
		action.setArgumentValue(AVTransport.UNIT, "REL_TIME"/*AVTransport.RELTIME maybe error*/);
		action.setArgumentValue(AVTransport.TARGET, String.format("%d:%02d:%02d", h, m, s));
		
		return action.postControlAction();
	}

	public boolean pauseRenderer() {
		if (null == selectedRendererUdn)
			return false;
		
		Device dev = getDevice(selectedRendererUdn);		
		if (dev == null)
			return false;
		
		Service avTransService = dev.getService(AVTransport.SERVICE_TYPE);
		if (avTransService == null)
			return false;
		
		Action action = avTransService.getAction(AVTransport.PAUSE);
		if (action == null)
			return false;
		
		action.setArgumentValue(AVTransport.INSTANCEID, "0");
		
		return action.postControlAction();
	}
	
	public String getProtocolInfo(String url, String fileName) {
		//<protocol>“:”<network>“:”<contentFormat>“:”<additionalInfo>		
		return getProtocol(url) + ":*:" + getContentFormat(fileName) + ":*";
	}
	
	protected String getProtocol(String url) {
		if (url.startsWith("http://"))
			return UPNP_PROTOCOLINFO_PROTOCOL_HTTPGET;
		else if (url.startsWith("rtsp://"))
			return UPNP_PROTOCOLINFO_PROTOCOL_RTSP;
		else 
			return "*";
	}
	
	protected String getContentFormat(String fileName) {
		int suffixIndex = fileName.lastIndexOf('.');
		if (0 >suffixIndex)
			return "*";
		
		String ret = mmtypes.get(fileName.substring(suffixIndex+1).toLowerCase());
		if (null == ret)
			ret = "*";

		return ret;
	}
	
	public ArgumentList getRendererPositionInfo() {
		
		if (null == selectedRendererUdn)
			return null;
		
		Device dev = getDevice(selectedRendererUdn);		
		if (dev == null)
			return null;

		Service avTransService = dev.getService(AVTransport.SERVICE_TYPE);
		if (avTransService == null)
			return null;
		
		Action action = avTransService.getAction(AVTransport.GETPOSITIONINFO);
		if (action == null)
			return null;
		
		action.setArgumentValue(AVTransport.INSTANCEID, "0");
		
		if(!action.postControlAction())
			return null;
		
		return action.getOutputArgumentList();
		
	}
	
	
	
}
